package uit.nfcmenu.activity;

import uit.nfcmenu.R;
import uit.nfcmenu.manager.AssetsManager;
import uit.nfcmenu.util.CommConstant;
import uit.nfcmenu.util.UiUtilities;
import uit.nfcmenu.util.Utilities;
import uit.nfcmenu.webservice.PreferenceHelper;
import uit.nfcmenu.webservice.UserModel;
import uit.nfcmenu.webservice.WSMapping;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

public class LoginActivity extends BaseActivity implements OnClickListener {
	String tag = LoginActivity.class.getSimpleName();
	
	private TextView tvRestaurantName;
	private TextView tvDeviceId;
	
	private Button[] arrBtnFlags = new Button[3];
	
	private EditText txtUserName;
	private EditText txtPassword;
	
	private RadioButton rbWaiter;
	private RadioButton rbChef;
	
	private Button btnLogin;
	private Button btnCancel;

	UserModel user;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		initView();
		initData();
		initListener();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		txtPassword.setText("");
		String language = PreferenceHelper.loadLanguage(mContext);
		changeLanguage(language);
		txtUserName.setText(PreferenceHelper.loadUsername(mContext));	

		
		// FIXME hard code 4 test >
//		PreferenceHelper.saveUsername(mContext, "user");
//		PreferenceHelper.saveDeviceId(mContext, "1");
//		PreferenceHelper.saveRestaurantId(mContext, "2");
//		PreferenceHelper.saveRestaurantName(mContext, "Lanna test");
//		Log.i(tag, "1px = "+UiUtilities.convertPixelsToDp(mContext, 1)+"dp");
		
		txtUserName.setText("user");
		txtPassword.setText("123456");
//		btnLogin.performClick();
		// />
	}

	private void initResNameAndDevName() {		
		// restaurant's name
		String restaurentName = PreferenceHelper.loadRestaurantName(mContext);
		if (!"".equals(restaurentName)) {
			tvRestaurantName.setText(restaurentName);
		} else {
			tvRestaurantName.setText(R.string.restaurant);
		}
		
		String deviceName = PreferenceHelper.loadDeviceName(mContext);
		if (!"".equals(deviceName)) {
			String device = mRes.getString(R.string.device);
			tvDeviceId.setText(device + " " + deviceName);
		} else {
			tvDeviceId.setText(R.string.device);
		}

		PreferenceHelper.saveRestaurantName(mContext, restaurentName);
	}
	
	@Override
	protected Context getActivityContext() {
		return this;
	}

	protected void initView() {
		tvRestaurantName = (TextView) findViewById(R.id.tvRestaurantName);
		tvDeviceId = (TextView) findViewById(R.id.tvDeviceId);
		txtUserName = (EditText) findViewById(R.id.txtUsername);
		txtPassword = (EditText) findViewById(R.id.txtPassword);
		
		arrBtnFlags[CommConstant.LANGUAGE_EN_INDEX] = (Button) findViewById(R.id.btnFlagEn);
		arrBtnFlags[CommConstant.LANGUAGE_JA_INDEX] = (Button) findViewById(R.id.btnFlagJa);
		arrBtnFlags[CommConstant.LANGUAGE_VI_INDEX] = (Button) findViewById(R.id.btnFlagVi);
		
		rbWaiter = (RadioButton) findViewById(R.id.rbWaiter);
		rbChef = (RadioButton) findViewById(R.id.rbChef);
		
		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnCancel = (Button) findViewById(R.id.btnCancel);
		
		AssetsManager.setCommonAppFont(mContext, tvDeviceId);
		AssetsManager.setCommonAppFont(mContext, tvRestaurantName);
	}

	protected void initData() {
		CommConstant.ARR_LANGUAGE = mRes.getStringArray(R.array.arr_language_signs);

		// TODO keep
//		ArrayAdapter<CharSequence> adapter;
//		adapter = ArrayAdapter.createFromResource(this, R.array.arr_languages,
//				android.R.layout.simple_spinner_item);
//		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//		spinner.setAdapter(adapter);

		// create folder contain data if not exist
//		File folder = new File("/sdcard/visualmenu");
//		if (!folder.exists()) {
//			folder.mkdir();
//		}
		
		initResNameAndDevName();
		initRole(true); // default is waiter in screen
		
		// check server
		// CommUrl.getServer();
		// new GetDataAsyncTask().execute(null);

		// make sure login without bad request cause by link not register US 
		// Utilities.pushCertificateSSL();
		Utilities.trustEveryoneTLS();
	}

	protected void initListener() {
		// TODO keep
//		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
//
//			@Override
//			public void onItemSelected(AdapterView<?> arg0, View arg1,
//					int position, long arg3) {
//				Log.i(tag, "spinner.onItemSelected() at " + position);
//				changeLanguage(CommConstant.ARR_LANGUAGE[position]);
//			}
//
//			@Override
//			public void onNothingSelected(AdapterView<?> arg0) {
//				Log.i(tag, "spinner.onNothingSelected()");
//			}
//		});
		
		arrBtnFlags[CommConstant.LANGUAGE_EN_INDEX].setOnClickListener(this);
		arrBtnFlags[CommConstant.LANGUAGE_JA_INDEX].setOnClickListener(this);
		arrBtnFlags[CommConstant.LANGUAGE_VI_INDEX].setOnClickListener(this);

		rbWaiter.setOnClickListener(this);
		rbChef.setOnClickListener(this);
		
		btnLogin.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
	}

	@Override
	protected void changeLanguage(String language) {
		Log.i(tag, "changeLanguage(" + language + ")");
		super.changeLanguage(language);

		PreferenceHelper.saveLanguage(mContext, language);

		((TextView) findViewById(R.id.tvLanguage)).setText(mRes.getString(R.string.language));
		((TextView) findViewById(R.id.tvUsername)).setText(mRes.getString(R.string.username));
		((TextView) findViewById(R.id.tvPassword)).setText(mRes.getString(R.string.password));
		((TextView) findViewById(R.id.tvRole)).setText(mRes.getString(R.string.role));
		((RadioButton) findViewById(R.id.rbWaiter)).setText(mRes.getString(R.string.waiter));
		((RadioButton) findViewById(R.id.rbChef)).setText(mRes.getString(R.string.chef));
		((Button) findViewById(R.id.btnLogin)).setText(mRes.getString(R.string.login));
		((Button) findViewById(R.id.btnCancel)).setText(mRes.getString(R.string.cancel));
		
		// set focus for textView Restaurant name and Device name
		initResNameAndDevName();

		// set focus for flags
		int languageIndex = CommConstant.getLanguageIndex(language);
		for (int i = 0; i < arrBtnFlags.length; i++) {
			arrBtnFlags[i].setSelected(i == languageIndex);
		}
	}

	@Override
	public void onClick(View v) {
		UiUtilities.hideKeyboard(mContext, txtPassword);
		
		int languageIndex = -1;
		switch (v.getId()) {
		case R.id.btnFlagEn:
			languageIndex = CommConstant.LANGUAGE_EN_INDEX;
			break;
	
		case R.id.btnFlagJa:
			languageIndex = CommConstant.LANGUAGE_JA_INDEX;
			break;
			
		case R.id.btnFlagVi:
			languageIndex = CommConstant.LANGUAGE_VI_INDEX;
			break;
			
		case R.id.rbWaiter:
			initRole(true);
			break;
	
		case R.id.rbChef:
			initRole(false);
			break;
			
		case R.id.btnLogin:
//			goNextActivity();
			doIfMeetNetworkOrShowFailStatus(mContext, SHOW_MESSAGE_ON_DIALOG,
					new Runnable() { @Override public void run() {
						new DoLogin().execute();
			}});
			break;
			
		case R.id.btnCancel:
			finish();
			break;
		} 
		if (languageIndex != -1) {
//			setLanguageOnFlagView(languageIndex);
			changeLanguage(CommConstant.ARR_LANGUAGE[languageIndex]);
		}
	}

	private void initRole(boolean isWaiter) {
		Log.i(tag, "initRole() isWaiter="+isWaiter);
		CommConstant.isWaiter = isWaiter;
		if (isWaiter) {
			if (!rbWaiter.isChecked()) {
				rbWaiter.setChecked(true);
			}
		} else {
			if (!rbChef.isChecked()) {
				rbChef.setChecked(true);
			}
		}
	}

	private class DoLogin extends BaseLoader {
		String username;
		String password;
		String deviceId;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			username = txtUserName.getText().toString();
			password = txtPassword.getText().toString();
			deviceId = PreferenceHelper.loadDeviceId(mContext);
			if (PreferenceHelper.DEFAULT_DEVICE_ID.equals(deviceId)) {
				deviceId = Utilities.getStringNotNull(UiUtilities.getMacAddress(mContext));
				PreferenceHelper.saveDeviceId(mContext, deviceId);
			}
		}

		@Override
		protected Integer doInBackground(Void... params) {
			try {
				boolean logout = WSMapping.logout(username, deviceId);
				Log.w(tag, "logout="+logout);
				user = WSMapping.login(mContext, username, password, deviceId);
				Log.w(tag, "user="+user.toString());
			} catch (Exception e) {
				Log.e(tag, "Error "+e);
			}
			return super.doInBackground(params);
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			UiUtilities.hideKeyboard(mContext, txtPassword);
			
			String token = (user == null) ? null : user.getUserToken();
			// login success
			if (token != null && !CommConstant.SIGN_EMPTY.equals(token)) {
				PreferenceHelper.saveUsername(mContext, username);
				PreferenceHelper.saveDeviceName(mContext, user.getDeviceName());
				PreferenceHelper.saveRestaurantId(mContext, user.getCompanyId());
				PreferenceHelper.saveRestaurantName(mContext, user.getCompanyName());
				PreferenceHelper.saveUserToken(mContext, user.getUserToken());
				initResNameAndDevName();
				
				goNextActivity();
			}
			// login fail
			else {
				UiUtilities.popupAlertMessage(mContext, 
						R.string.message, R.string.mess_login_fail, R.string.ok);
			}
		}
	}
	
	private void goNextActivity() {
		Log.i(tag, "goNextActivity(): CommConstant.isWaiter="+CommConstant.isWaiter);		
		Intent serviceIntent = new Intent(LoginActivity.this, BackGroundSync.class);
		startService(serviceIntent);
		Intent intent = (CommConstant.isWaiter) 
				? new Intent(mContext, WaiterMenuActivity.class)
				: new Intent(mContext, OrderActivity.class);
		startActivity(intent);
	}
}